﻿using System;
using System.Linq;
using K9Nano.Storage;
using K9Nano.Storage.Local.Internal;
using Microsoft.Extensions.Configuration;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class LocalStorageStartupExtensions
    {
        public static IServiceCollection AddLocalStorage(this IServiceCollection services, Action<LocalFileStorageOptions> configureOption)
        {
            services.Configure(configureOption);
            services.AddSingleton<IFileStorage, LocalFileStorage>();
            return services;
        }

        public static IServiceCollection AddLocalStorage(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<LocalFileStorageOptions>(configuration);
            services.AddSingleton<IFileStorage, LocalFileStorage>();
            return services;
        }

        private static void AddLocalStorageInternal(IServiceCollection services)
        {
            services.PostConfigure<LocalFileStorageOptions>(options =>
            {
                if (string.IsNullOrEmpty(options.Path))
                {
                    throw new ArgumentException("文件存储路径不能为空");
                }

                if (string.IsNullOrEmpty(options.MaxLength))
                {
                    throw new ArgumentException("文件大小限制不能为空");
                }

                var unit = options.MaxLength.Last().ToString();
                if (!unit.Equals("K", StringComparison.OrdinalIgnoreCase)
                    && !unit.Equals("M", StringComparison.OrdinalIgnoreCase)
                    && !unit.Equals("G", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException("文件大小限制只能以K、M或者G结尾");
                }
            });

            services.AddSingleton<IFileStorage, LocalFileStorage>();
        }
    }
}
